package com.technology.education.ui.teacher.order_detail

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.view.Gravity
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.view.marginLeft
import androidx.core.view.setPadding
import androidx.lifecycle.lifecycleScope
import cn.jzvd.JzvdStd
import com.angcyo.dsladapter.dpi
import com.angcyo.dsladapter.dslItem
import com.angcyo.dsladapter.findItemByTag
import com.google.android.material.imageview.ShapeableImageView
import com.technology.education.R
import com.technology.education.base.BaseRecyclerTopBarFragment
import com.technology.education.data.SpKeys
import com.technology.education.data.model.TeacherOrderDetailModel
import com.technology.education.dslitem.ItemColumnTitleText
import com.technology.education.dslitem.ItemSingleButton
import com.technology.education.dslitem.ItemSingleImage
import com.technology.education.dslitem.ItemSingleText
import com.technology.education.dslitem.module.ItemOrderStatusCountdown
import com.technology.education.ext.*
import com.technology.education.ui.common.board_video.BoardVideoActivity
import com.technology.education.ui.common.video_play.VideoPlayActivity
import com.technology.education.utils.LogUtil
import com.technology.education.utils.rom.*
import com.technology.education.widget.CommonButton
import com.tencent.android.tpush.XGPushManager
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.dp2px
import me.hgj.jetpackmvvm.util.LogUtils
import me.hgj.jetpackmvvm.util.startActivity
import java.lang.IndexOutOfBoundsException
import java.util.*

/**
 * 教师端订单详情
 */
class OrderDetailFragment : BaseRecyclerTopBarFragment<OrderDetailViewModel>() {
    override fun initViews() {
        setTitle("订单详情")
        mViewModel.orderId = arguments?.getString("id") ?: ""
        initGrid(4)
    }

    override fun lazyLoadData() {
        loading()
    }

    private fun setUI(info: TeacherOrderDetailModel) {
        renderAdapter {
            clearAllItems()
            dslItem(ItemSingleText(info.teacherStatusInfo, itemSpan = -1)) {
                style.itemSpan = -1
                style.titleTextSize = 18f
                style.isBold = true
                style.bottomPadding = 2
                style.titleTextColor = R.color.theme_color
                itemPaddingTop = 20 * dpi
            }
            if (info.teachOrderState == "1") {
                //派单状态展示接单提示
                if (info.appointMe == "1") {
                    ///如果自己为指定老师,则显示倒计时
                    if (info.remainDuration > 0) {
                        dslItem(
                            R.layout.item_order_status_countdown
                        ) {
                            itemTag = "countdown"
                            itemSpanCount = -1
                            itemBindOverride = { itemHolder, _, _, payloads ->
                                itemHolder.tv(R.id.tv_status)?.apply {
                                    setTextColor(getColor(R.color.red))
                                    text =
                                        "${
                                            if (payloads.isEmpty())
                                                formatTime(
                                                    info.remainDuration / 1000
                                                )
                                            else payloads[0].toString()
                                        }后未接单,其他老师可进行抢单"
                                }
                            }
                        }
                        startCountDown(info.remainDuration, info.id)
                    }

                } else {
                    //非指定老师显示提示语
                    dslItem(
                        ItemOrderStatusCountdown(
                            formatTime(info.remainDuration),
                            "countdown"
                        )
                    ) {
                        itemTag = "countdown"
                        itemSpanCount = -1
                        itemBindOverride = { itemHolder, _, _, _ ->
                            itemHolder.tv(R.id.tv_status)?.apply {
                                text = "您不是指定的老师,暂时不可以接单"
                                setTextColor(getColor(R.color.red))
                            }
                            itemHolder.gone(R.id.progress)
                        }
                    }
                }
            }
            if (info.teachOrderState == "3") {
                //接单成功,显示发起视频倒计时
                if (info.remainDuration > 0) {
                    dslItem(
                        R.layout.item_order_status_countdown
                    ) {
                        itemTag = "countdown"
                        itemSpanCount = -1
                        itemBindOverride = { itemHolder, _, _, payloads ->
                            itemHolder.tv(R.id.tv_status)?.apply {
                                setTextColor(getColor(R.color.red))
                                text =
                                    "${
                                        if (payloads.isEmpty())
                                            formatTime(
                                                info.remainDuration / 1000
                                            )
                                        else payloads[0].toString()
                                    }后未发起视频,将交由其他老师辅导"
                            }
                        }
                    }
                    startCountDown(info.remainDuration, info.id)
                }
            }
            dslItem(R.layout.item_grab_order_flow)
            {
                itemSpanCount = -1
                itemTopInsert = 16 * dpi
            }
            dslItem(ItemSingleText("问题图片", itemSpan = -1)) {
                style.itemSpan = -1
                style.isBold = true
            }

            info.questionImages?.let {
                it.forEachIndexed { index, url ->
                    dslItem(R.layout.item_order_image) {
                        itemSpanCount = 2
                        itemBindOverride = { itemHolder, _, _, _ ->
                            itemSpanCount = 2
                            itemHolder.click(R.id.tv_preview) { _ ->
                                toPreviewPhoto(index, it as ArrayList<String>)
                            }
                            itemHolder.click(R.id.tv_down) {
                                downImage(url)

                            }
                            itemHolder.v<ShapeableImageView>(R.id.image)?.apply {
                                loadImage(url, this)
                            }
                            itemHolder.clickItem { _ ->
                                toPreviewPhoto(index, it as ArrayList<String>)
                            }
                        }
                    }
                }
            }

            info.question?.let {
                //问题描述
                dslItem(ItemSingleText("问题描述", itemSpan = -1)) {
                    itemSpanCount = -1
                    style.lineHeight = 0
                    style.bottomPadding = 10
                    style.isBold = true
                }
                dslItem(ItemSingleText(it)) {
                    itemLeftInsert = 12 * dpi
                    itemRightInsert = 12 * dpi
                    style.lineColor = R.color.white
                    style.topPadding = 10
                    style.bottomPadding = 10
                    style.leftPadding = 12
                    style.rightPadding = 12
                    style.itemBackDrawable = R.drawable.round_gray
                    style.itemBackColor = 0
                    style.lineHeight = 0
                }
            }

            info.answer?.let {
                //辅导笔记展示
                dslItem(ItemSingleText("辅导笔记", itemSpan = -1)) {
                    itemSpanCount = -1
                    style.lineHeight = 0
                    style.bottomPadding = 0
                    style.isBold = true
                }
                dslItem(ItemSingleText(it)) {
                    itemLeftInsert = 12 * dpi
                    itemRightInsert = 12 * dpi
                    style.lineColor = R.color.white
                    style.topPadding = 10
                    style.bottomPadding = 10
                    style.leftPadding = 12
                    style.rightPadding = 12
                    style.itemBackDrawable = R.drawable.round_gray
                    style.itemBackColor = 0
                    style.lineHeight = 0
                }
            }
            if (!info.answerImages.isNullOrEmpty()) {
                info.answerImages.forEach {
                    dslItem(ItemSingleImage(it, size = 80 * dpi)) {
                        itemSpanCount = 1
                    }
                }
            }


            info.videoUrl?.let { url ->
                dslItem(ItemColumnTitleText("辅导视频", content = "(30天内可以回看)")) {
                    itemSpanCount = -1
                    style.contentTextSize = 12f
                    style.lineHeight = 0
                    style.bottomPadding = 0
                    style.contentTextColor = R.color.text_m
                    style.contentGravity = Gravity.BOTTOM or Gravity.LEFT
                    style.isBold = true
                }
                dslItem(R.layout.item_order_video) {
                    itemBindOverride = { itemHolder, _, _, _ ->
                        itemSpanCount = -1
                        itemHolder.v<ImageView>(R.id.video)?.apply {
                            loadImageVideo(url, this)
                        }
                        itemHolder.click(R.id.iv_play) { _ ->
                            startActivity(
                                VideoPlayActivity::class, Pair("url", url),
                                Pair("title", "辅导回看"), Pair("answer", info.answer ?: ""),
                                Pair(
                                    "image",
                                    (info.answerImages ?: arrayListOf()) as ArrayList<String>
                                )
                            )
                        }
                    }
                }
            }

            dslItem(ItemSingleText("订单信息", itemSpan = -1)) {
                itemSpanCount = -1
                style.isBold = true
            }
            dslItem(ItemColumnTitleText("订单编号", content = info.id)) {
                style.titleTextColor = R.color.text_m
                style.contentTextColor = R.color.text_m
                style.contentGravity = Gravity.RIGHT
                style.lineHeight = 0
                style.topPadding = 0
                itemSpanCount = -1
            }
            dslItem(ItemColumnTitleText("订单时间", content = info.placeTime)) {
                style.titleTextColor = R.color.text_m
                style.contentTextColor = R.color.text_m
                style.contentGravity = Gravity.RIGHT
                style.lineHeight = 0
                style.topPadding = 0
                itemSpanCount = -1
            }
            info.takeTime?.let {
                dslItem(ItemColumnTitleText("接单时间", content = it)) {
                    style.titleTextColor = R.color.text_m
                    style.contentTextColor = R.color.text_m
                    style.contentGravity = Gravity.RIGHT
                    style.lineHeight = 0
                    style.topPadding = 0
                    itemSpanCount = -1
                }
            }
            info.startTime?.let {
                dslItem(ItemColumnTitleText("辅导开始时间", content = it)) {
                    style.titleTextColor = R.color.text_m
                    style.contentTextColor = R.color.text_m
                    style.contentGravity = Gravity.RIGHT
                    style.lineHeight = 0
                    style.topPadding = 0
                    itemSpanCount = -1
                }
            }
            info.endTime?.let {
                dslItem(ItemColumnTitleText("辅导结束时间", content = it)) {
                    style.titleTextColor = R.color.text_m
                    style.contentTextColor = R.color.text_m
                    style.contentGravity = Gravity.RIGHT
                    style.lineHeight = 0
                    style.topPadding = 0
                    itemSpanCount = -1
                }
                dslItem(ItemColumnTitleText("辅导总时长", content = info?.durationStr)) {
                    style.titleTextColor = R.color.text_m
                    style.contentTextColor = R.color.text_m
                    style.contentGravity = Gravity.RIGHT
                    style.lineHeight = 0
                    style.topPadding = 0
                    itemSpanCount = -1
                }
            }

        }
        if (info.showTakeButton) {
            when (info.teachOrderState) {
                "3" -> {
                    setBottomButton("发起辅导") {
                        startTeach()
                    }
                }
                "4" -> {
                    bottomContent().apply {
                        removeAllViews()
                        setPadding(12 * dpi)
                        addView(
                            CommonButton(requireContext()).apply {
                                weightSum = 1f
                                text = "结束辅导"
                                textSize = 16f
                                setOnClickListener {
                                    mViewModel.finishOrder()
                                }
                            },
                            ViewGroup.LayoutParams(
                                getScreenWide() / 2 - dp2px(24),
                                dp2px(45)
                            ).apply {
                                weightSum = 1.0f
                            }
                        )

                        addView(
                            CommonButton(requireContext()).apply {
                                weightSum = 1f
                                text = "发起辅导"
                                textSize = 16f
                                setOnClickListener {
                                    startTeach()
                                }
                            },
                            ViewGroup.MarginLayoutParams(
                                getScreenWide() / 2 - dp2px(24),
                                dp2px(45)
                            ).apply {
                                weightSum = 1.0f
                                marginStart = dp2px(16)
                            }
                        )
                    }

                }
                else -> {
                    setBottomButton("立即抢单") {
                        mViewModel.takeOrder()
                    }
                }
            }

        }
    }

    private fun getRoomId(): Int {
        return if (mViewModel.orderId.isEmpty()) generateRoomID() else mViewModel.orderId.substring(
            10
        ).toInt()
    }

    private fun startTeach() {
//        videoCall(mViewModel.orderId, mViewModel.studentId, getRoomId())
//        mViewModel.startTeach()
//        return
        if (checkAlertPermission()) {
            videoCall(mViewModel.orderId, mViewModel.studentId, getRoomId())
            mViewModel.startTeach()
        } else {
            notifyDialog(notify = "为了更好的进行视频辅导,请开启悬浮窗权限", confirm = {
                SettingsCompat.manageDrawOverlays(requireContext())
//                when {
//                    RomUtils.checkIsMiuiRom() -> {
//                        MiuiUtils.applyMiuiPermission(context)
//                    }
//                    RomUtils.checkIsMeizuRom() -> {
//                        MeizuUtils.applyPermission(context)
//                    }
//                    RomUtils.checkIsHuaweiRom() -> {
//                        HuaweiUtils.applyPermission(context)
//                    }
//                    RomUtils.checkIs360Rom() -> {
//                        QikuUtils.applyPermission(context)
//                    }
//                    RomUtils.checkIsOppoRom() -> {
//                        OppoUtils.applyOppoPermission(context)
//                    }
//                    else -> {
//                        commonROMPermissionApplyInternal(requireContext())
//                    }
//                }
            }, cancel = {
                toast("稍后可以在设置->应用->权限管理中开启悬浮窗权限")
                videoCall(mViewModel.orderId, mViewModel.studentId, getRoomId())
                mViewModel.startTeach()
            })
        }
    }

    private fun showAlertPermission() {
        if (!checkAlertPermission()) {

            notifyDialog(notify = "为了更好的进行视频辅导,请开启悬浮窗权限", confirm = {
                SettingsCompat.manageDrawOverlays(requireContext())
//                when {
//                    RomUtils.checkIsMiuiRom() -> {
//                        MiuiUtils.applyMiuiPermission(context)
//                    }
//                    RomUtils.checkIsMeizuRom() -> {
//                        MeizuUtils.applyPermission(context)
//                    }
//                    RomUtils.checkIsHuaweiRom() -> {
//                        HuaweiUtils.applyPermission(context)
//                    }
//                    RomUtils.checkIs360Rom() -> {
//                        QikuUtils.applyPermission(context)
//                    }
//                    RomUtils.checkIsOppoRom() -> {
//                        OppoUtils.applyOppoPermission(context)
//                    }
//                    else -> {
//                        commonROMPermissionApplyInternal(requireContext())
//                    }
//                }
            }, cancel = {
                toast("稍后可以在设置->应用->权限管理中开启悬浮窗权限")
            })
        }
    }

    private fun commonROMPermissionApplyInternal(context: Context) {
        val clazz: Class<*> = Settings::class.java
        val field =
            clazz.getDeclaredField("ACTION_MANAGE_OVERLAY_PERMISSION")
        val intent = Intent(field[null].toString())
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent.data = Uri.parse("package:" + context.packageName)
        context.startActivity(intent)
    }

    var timer: Timer? = null
    private fun startCountDown(timeDiff: Int, orderId: String) {
        var time = timeDiff / 1000
        if (timer == null) {
            timer = Timer()
            timer!!.schedule(object : TimerTask() {
                override fun run() {
                    time--
                    if (time > 0) {
                        renderAdapter {
                            findItemByTag("countdown")?.let {
                                myAdapter.notifyItemChanged(
                                    it, formatTime(
                                        time
                                    )
                                )
                            }
                        }
                    } else {
                        timer!!.cancel()
                        refreshData()
                        ///指定教师超时未接单,则需改状态为2
                        postEventBus(SpKeys.CHANGE_ORDER_STATUS_TAKE, orderId)
                    }

                }

            }, 1000, 1000)
        }

    }

    override fun onPause() {
        super.onPause()
        JzvdStd.releaseAllVideos()
    }


    override fun createObserver() {
        observe(SpKeys.START_VIDEO, String::class.java) {
            ///视频接通则调用接口开始辅导
//            if (mViewModel.orderId == it) {
//                mViewModel.startTeach()
//            }
        }
        observe(SpKeys.FINISH_VIDEO, String::class.java) {
            ///如果通话结束,则调用结束接口
            if (mViewModel.orderId == it) {
                mViewModel.finishOrder()
            }
        }
        /**
         * 教师结束辅导
         */
        observe(SpKeys.CHANGE_ORDER_STATUS_WAIT_EVALUATE, String::class.java) {
            if (it == mViewModel.orderId) {
                getAppViewModel().pushMessage(
                    it,
                    SpKeys.CHANGE_ORDER_STATUS_WAIT_EVALUATE,
                    mViewModel.studentId
                )
                toast("辅导已结束")
                onBack()
            }
        }

        /**
         * 教师开始辅导
         */
        observe(SpKeys.CHANGE_ORDER_STATUS_START, String::class.java) {
            dismissLoading()
            if (it == mViewModel.orderId) {
                refreshData()
            }
        }
        /**
         * 接单结果
         */
        mViewModel.takeResult.observe(this) {
            if (it.state == "0") {
                //接单成功之后更改底部按钮提示信息,修改订单状态
                postEventBus(SpKeys.REMOVE_ORDER_FROM_LIST, mViewModel.orderId)
                refreshData()
                setBottomButton("发起辅导") {
                    startTeach()
                }
                toast("您已成功接单")
            } else if (it.state == "1") {
                mViewModel.commitOrder()
            }
        }
        /**
         * 获取订单详情
         */
        mViewModel.result.observe(this) {
            parseState(it, onSuccess = { it ->
                timer?.cancel()
                timer = null
                mViewModel.studentId = it.student.id
                try {
                    setUI(it)
                } catch (e: IndexOutOfBoundsException) {
                    showLog(e.toString())
                }
                if (it.teachOrderState == "3" || it.teachOrderState == "4") {
                    showAlertPermission()
                }
            }, onError = { err ->
                toast(err.errorMsg)
            })
        }

        mViewModel.resultCharge.observe(this) {
            parseState(it, onSuccess = { it ->
                toPayActivity(it.money.toString(), it.id, SpKeys.PAY_TYPE_DEPOSIT)
            }, onError = { err -> toast(err.errorMsg) })
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        timer?.cancel()
        timer = null
    }
}